package com.jungle.bfi.generator;

import com.jungle.bfi.generator.config.Config;
import com.jungle.bfi.generator.config.GeneratorCfg;
import com.jungle.bfi.generator.config.PositionCfg;
import com.jungle.bfi.generator.config.SourceType;
import org.yaml.snakeyaml.Yaml;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URL;
import java.nio.file.Path;

public class ConfigLoader {
    public static Config load(File configFile) throws IOException {

        Yaml yaml = new Yaml();
        try (FileInputStream fos = new FileInputStream(configFile)) {
            Config config = yaml.loadAs(fos, Config.class);
            if (config == null) {
                config = new Config();
            }
            if (config.getGenerator() == null) {
                config.setGenerator(new GeneratorCfg());
            }
            GeneratorCfg generator = config.getGenerator();
            if (generator.getGlobalPosition() == null) {
                generator.setGlobalPosition(new PositionCfg());
            }
            PositionCfg globalPosition = generator.getGlobalPosition();
            if (globalPosition.getSourceType() == null) {
                globalPosition.setSourceType(SourceType.JAVA);
            }
            if (globalPosition.getSource() == null) {
                globalPosition.setSource("src/main/java");
            }
            if (globalPosition.getResource() == null) {
                globalPosition.setResource("src/main/resources");
            }

            return config;
        }
    }

    public static void main(String[] args) {
        URL resource = ConfigLoader.class.getClassLoader().getResource(".");
        assert resource != null;
        System.out.println(resource.getFile());
        Path path = Path.of(resource.getPath());
        System.out.println(path);
        Path projectPath = path.getParent().getParent();
        System.out.println(projectPath);
        Path configPath = projectPath.resolve("src/main/resources/GeneratorConfig.yml");
        try {
            Config config = load(configPath.toFile());
            System.out.println(config);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
